home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2268 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.2 KB

  1. Path: news.magi.com!news!news.magi.com
  2. From: nredding@magi.com (Neil Redding)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Fri, 19 Jan 1996 22:45:36 -0500
  6. Organization: Magi Data Consulting
  7. Message-ID: <nredding-1901962245370001@magi04p72.magi.com>
  8. References: <4dorr8$i58@cloner3.netcom.com> <4dp5dk$t3r@newsbf02.news.aol.com>
  9. NNTP-Posting-Host: magi04p72.magi.com
  10.  
  11. In article <4dp5dk$t3r@newsbf02.news.aol.com>, babycox@aol.com (BabyCox) wrote:
  12.  
  13. >>#define ISPOW2(x) (((x) & 1) ^ 1)
  14. >
  15. >That will not work, it returns the next lowest MULTIPLE of two, here's
  16. >what I would do:
  17. >
  18. >Boolean IsPowerOfTwo(long x)
  19. >{
  20. >  for(short y = 0;y<=31;y++)
  21. >  {
  22. >    if (x = 1) return true;
  23. >    x >>= 1;
  24. >  }
  25. >  return false;
  26. >}
  27.  
  28. Even worse, this returns true unless x == 0.
  29.  
  30. If n is a power of 2, repeatedly multiplying n by 2 will eventually give you
  31. 2**32 == 0 when it overflows. Also shifting left one bit ( n<<1) is the same
  32. as multiplying by 2.
  33. Thus:
  34.  
  35.  
  36. Boolean IsPowerOfTwo( unsigned long n )
  37. {
  38.    short k = 31;
  39.    if ( n == 0 )
  40.        return false;
  41.   while ( k--  > 0 )
  42.         if ( (n <<= 1 ) == 0 )
  43.               return true;
  44.   return false;
  45. }
  46.  
  47. -- 
  48. Neil Redding
  49. Ottawa, Canada
  50.